﻿using CCManger.Common.Message;
using DotNetty.Handlers.Timeout;
using DotNetty.Transport.Channels;
using Serilog;
using System;
using System.Net;
using System.Threading.Tasks;

namespace CCManger.ModuleSocket.ClientSocket
{
    public class ClientHandler:ChannelHandlerAdapter
    {
        public IChannelHandlerContext _Socket;

        public event CommandReceiveEvent MessageReceived;

        public event MessageSendEvent MessageSend;

        public async void SendData<T>(T obj)
        {
            try
            {
                await _Socket.WriteAndFlushAsync(obj);
            }
            catch (Exception ex) { }
        }

        private void OnMessageReceive(Message msg) => MessageReceived?.Invoke(this, new MessageEventArgs(msg));

        private void OnMessageSend(Message msg) => MessageSend?.Invoke(this, new MessageEventArgs(msg));

        public override async void ChannelActive(IChannelHandlerContext context)
        {
            //Log.Debug("我是客户端.");
            //Log.Debug($"连接至服务端{context}.");

            //编码器,发送至服务端
            //string message = "客户端1";
            //context.WriteAndFlushAsync(message);

            await Task.Run(() =>
            {
                Message ms = new Message { Command = COMMAND.Message, Content = $"客户端{(context.Channel.LocalAddress as IPEndPoint).Port}" };
                Message message = new Message
                {
                    Command = COMMAND.ClientToServer,
                    Eoperation = Operation.OnlineNotify,
                    SenderInfo = new SenderInfo { ID = Guid.NewGuid().ToString("N"), Name = Environment.MachineName }
                };
                context.WriteAndFlushAsync(message);
                OnMessageSend(ms);
            });

            ////编码成IByteBuffer,发送至服务端
            //string message = "客户端1";
            //byte[] messageBytes = Encoding.UTF8.GetBytes(message);
            //IByteBuffer initialMessage = Unpooled.Buffer(messageBytes.Length);
            //initialMessage.WriteBytes(messageBytes);

            //context.WriteAndFlushAsync(initialMessage);
        }

        /// <summary>
        /// 心跳
        /// </summary>
        /// <param name="context"></param>
        /// <param name="evt"></param>
        public override async void UserEventTriggered(IChannelHandlerContext context, object evt)
        {
            await Task.Run(() =>
            {
                //Log.Debug("客户端循环心跳监测发送: " + DateTime.Now);
                if (evt is IdleStateEvent eventState)
                {
                    if (eventState.State == IdleState.WriterIdle)
                    {
                        Message ms = new Message { Command = COMMAND.HeartBeat, Content = $"biubiu:{DateTime.Now}" };
                        context.WriteAndFlushAsync(ms);
                        OnMessageSend(ms); //消息发送
                    }
                }
            });
        }

        public override async void ChannelRead(IChannelHandlerContext context, object message)
        {
            await Task.Run(() =>
            {
                if (message is Message oo)
                {
                    OnMessageReceive(oo);
                }
            });
        }

        public override void ChannelReadComplete(IChannelHandlerContext context) => context.Flush();

        public override void HandlerAdded(IChannelHandlerContext context)
        {

            //Log.Debug($"服务端{context}上线.");
            base.HandlerAdded(context);
            return;
            //await Task.Run(() =>
            //{
               
            //    Message message = new Message
            //    {
            //        Command = COMMAND.ClientToServer,
            //        Eoperation = Operation.OnlineNotify,
            //        SenderInfo = new SenderInfo { ID = Guid.NewGuid().ToString("N"), Name = Environment.MachineName }
            //    };
            //    context.WriteAndFlushAsync(message);
            //});
        }
      

        public override void HandlerRemoved(IChannelHandlerContext context)
        {
            //Log.Debug($"服务端{context}下线.");
            base.HandlerRemoved(context);
        }

    }
}
